import plays from './plays.json'
export default function statement(invoice, plays) {
  let totalAmount = 0;
  let volumeCredits = 0;
  let res = `【用户${invoice.customer}的票据单】`;
  // const format = new Intl.NumberFormat("en-US", {style: "currency", currency: "USD", minimumFractionDigits: 2}).format
  // 🔺第五步：将函数赋值给临时变量
  // 🔺第六步：改变函数声明 体现意图
  function usd(aNumber) {
    return new Intl.NumberFormat("en-US", {style: "currency", currency: "USD", minimumFractionDigits: 2}).format(aNumber)
  }
  for (let perf of invoice.performance) {
    // 🔺第四步：移除局部变量 thisAmount 【？这里为了重构多了查询和计算次数 这个如何取舍】
    // 【作者后来的解答是：大多数情况下的性能亏损是可以忽略不计的，先做重构，然后性能调优】
    // const thisAmount = amountFor(perf)
    // 新增数量分
    volumeCredits += volumeCreditsFor(perf)
    res += ` ${playFor(perf).name}: ${usd(amountFor(perf)/100)} (${perf.audience} 座)`;
    totalAmount += amountFor(perf);
  }
  res += ` 所欠贷款是 ${usd(totalAmount/100)}`;
  res += ` 你赚了 ${volumeCredits} 分`;
  return res;
} 

// 🔺第一步：提炼函数
function amountFor(aPerformance) {
  // 🔺第二步：优化变量名称
  let res = 0
  switch(playFor(aPerformance).type) {
    case "悲剧":
      res = 40000;
      if (aPerformance.audience > 30) {
        res += 1000 * (aPerformance.audience - 30);
      }
      break;
    case "喜剧": 
    res = 30000;
      if (aPerformance.audience > 20) {
        res += 10000 + 500 * (aPerformance.audience - 20);
      }
      res += 300 * aPerformance.audience
      break
    default:
      throw new Error(`未知的类型: ${play.type}`)
  }
  return res
}

// 🔺第三步：以查询取代临时变量
function playFor(aPerformance) {
  return plays[aPerformance.playID]
}

function volumeCreditsFor(aPerformance) {
  let res = 0;
  res += Math.max(aPerformance.audience - 30, 0);
  if ("喜剧" === playFor(aPerformance).type) res += Math.floor(aPerformance.audience / 5);
  return res;
}